<?php
/**
 * Created by PhpStorm.
 * User: XZR
 * Date: 2018/8/6
 * Time: 15:14
 */

namespace Admin\Model;



use Think\Model;

class UserModel extends Model
{
    protected $tablePrefix = "";
    protected $tableName = 'tb_md_user';

    /* 自动验证规则 */
    protected $_validate = array(
        array('name', 'require', '姓名必须', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('hospital', 'require', '医院必须', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    );

    private static $instance;

    public static function singleton()
    {
        self::$instance === null and self::$instance = new self();
        return self::$instance;
    }

    //获取记录总数
    public function getCount($map){
        return $this->where($map)->count()?: 0;
//         $new_map = [];
//         foreach ($map as $k => $v){
//             $new = 'u.' . $k;
//             $new_map[$new] = $v;
//         }
//         return $this->alias('u')->where($new_map)
//         ->join('tb_md_medical_record AS mr on u.id = mr.user_id')
//         ->count('distinct(u.id)');
    }

    public function getList($map,$limit){
        $new_map = [];
        foreach ($map as $k => $v){
            $new = 'u.' . $k;
            $new_map[$new] = $v;
        }
        return $this->alias('u')->where($new_map)
            ->join('tb_md_medical_record AS mr on u.id = mr.user_id',"LEFT")
            ->group('u.id')
            ->limit($limit)->order('u.id DESC')->field(['u.*', 'count(mr.id) as publish_count'])->select()?:[];
    }

    public function getOne($id){
        return $this->where(['id'=>$id])->find();
    }
    public function update(){
        /* 获取数据对象 */
       $data = $this->create($_POST);
       if(empty($data)){
           return false;
       }
        $res =$this->where(['id'=>$data['id']])->save($data);
        if(false === $res){
            $this->error = '更新文章出错！';
            return false;
        }
        return $data;
    }
}